package com.httpdemo.http_teaching_server.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/methods")
public class MethodMatrixController {

    /* 1. GET — 幂等 & 安全 */
    @GetMapping("/get/{id}")
    public Map<String, Object> get(@PathVariable Long id) {
        return Map.of("method", "GET", "id", id, "note", "幂等、安全、可缓存");
    }

    /* 2. POST — 非幂等 & 非安全 */
    @PostMapping("/post")
    public Map<String, Object> post() {
        return Map.of("method", "POST", "note", "非幂等、非安全、创建资源");
    }

    /* 3. PUT — 幂等 & 整体更新 */
    @PutMapping("/put/{id}")
    public Map<String, Object> put(@PathVariable Long id) {
        return Map.of("method", "PUT", "id", id, "note", "幂等、整体更新");
    }

    /* 4. PATCH — 非幂等 & 部分更新 */
    @PatchMapping("/patch/{id}")
    public Map<String, Object> patch(@PathVariable Long id) {
        return Map.of("method", "PATCH", "id", id, "note", "非幂等、部分更新");
    }

    /* 5. DELETE — 幂等 & 非安全 */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        return Map.of("method", "DELETE", "id", id, "note", "幂等、非安全");
    }

    /* 6. HEAD — 只返回头 */
    @RequestMapping(value = "/head/{id}", method = RequestMethod.HEAD)
    public ResponseEntity<Void> head(@PathVariable Long id) {
        return ResponseEntity.ok()
                .header("X-Method", "HEAD")
                .header("X-Resource-ID", id.toString())
                .build();
    }

    /* 7. OPTIONS — 查看允许方法 */
    @RequestMapping(value = "/options", method = RequestMethod.OPTIONS)
    public ResponseEntity<Void> options() {
        return ResponseEntity.ok()
                .header("Allow", "GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS,TRACE")
                .build();
    }

    /* 8. TRACE — 原样回显请求 */
    @RequestMapping(value = "/trace", method = RequestMethod.TRACE)
    public Map<String, Object> trace(HttpServletRequest request) {
        return Map.of(
                "method", "TRACE",
                "uri", request.getRequestURI(),
                "headers", Collections.list(request.getHeaderNames())
                        .stream()
                        .collect(Collectors.toMap(h -> h, request::getHeader))
        );
    }

    /* 9. CONNECT — 课堂演示 405 */
    @RequestMapping(value = "/connect", method = RequestMethod.TRACE)   // 先占位，实际用 405
    public ResponseEntity<Void> connect() {
        return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build();
    }
}